/**
 *  Eclipse Public License 1.0
 */
package org.fireblade.easysms;

import java.lang.reflect.Method;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * provides set foreground method for api <=4 and >4
 */
public abstract class AbstractService extends Service {
  /**
   * own log tag
   */
  private static final String LOGTAG = MainActivity.EASY_SMS + AbstractService.class.getSimpleName();

  // for api <= 4, we add our own notification
  private boolean ownNotificationAdded = false;


  /*
   * (non-Javadoc)
   * @see android.app.Service#onCreate()
   */
  @Override
  public void onCreate() {
    super.onCreate();
    Log.d(LOGTAG, "onCreate");
  }


  /*
   * (non-Javadoc)
   * @see android.app.Service#onDestroy()
   */
  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(LOGTAG, "onDestroy");
    if (ownNotificationAdded) {
      NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      manager.cancel(getNotificationId());
    } else {
      // will be removed by framework
    }
  }


  protected abstract int getNotificationId();


  protected abstract String getConnectionType();


  protected void setForeground() {
    int id = getNotificationId();
    // all apis, maybe no-op
    setForeground(true);

      Notification notification = createNotification();
      NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      manager.notify(id, notification);
      ownNotificationAdded = true;

  }


  protected Notification createNotification() {
    Notification notification = new Notification();
    notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
    notification.when = System.currentTimeMillis();
    // notification.tickerText = "EasySMS Service";
    notification.icon = R.drawable.notification;
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
    pi = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK);
    notification.setLatestEventInfo(this, "EasySMS Service", getResources().getString(R.string.service_running)
      + " (" + getConnectionType() + ")", pi);
    return notification;
  }


  /** ignore */
  @Override
  public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
  }
}
